<?php

namespace app\common\job;

use app\common\model\Landing;
use app\common\model\Member;
use app\common\model\Trade;
use app\common\service\TemplateSmsService;
use ShidianUtil\Utils\CheckUtil;
use think\queue\Job;

/**
 * 落地页未支付短信
 * Class SmsLanding
 * @package app\common\job
 */
class SmsLanding
{
    /**
     * fire是消息队列默认调用的方法
     * @param Job $job 当前的任务对象
     * @param array|mixed $data 发布任务时自定义的数据
     */
    public function fire(Job $job, $data)
    {
        $tradeId = $data['id'] ?? null;

        // 订单
        $trade = Trade::where('id', $tradeId)->find();
        if (is_null($trade) || $trade->payStatus == Trade::PAID) {
            $job->delete();
            return;
        }

        //落地页
        $landing = Landing::where('id', $trade->landingId)->find();
        if (is_null($landing) || $landing->status == 1) {
            $job->delete();
            return;
        }

        $phone = $landing->phone;
        if (!CheckUtil::isPhoneNumber($phone)) {
            $phone = Member::where('id', $landing->memberId)->value('phone');
            if (!CheckUtil::isPhoneNumber($phone)) {
                $job->delete();
                return;
            }
        }

        if ($landing->landingType === 'landing1') {
            $this->getTemplateSmsService()->memberLandingUnPay($phone, $tradeId);
        } elseif ($landing->landingType === 'landing2') {

            $rand = mt_rand(0, 1);

            $gid = $landing->promotionGroupId;

            if ($rand === 0) {
                $this->getTemplateSmsService()->remindPay1($phone, $gid);
            } else {
                $this->getTemplateSmsService()->remindPay2($phone, $gid);
            }
        }

        $job->delete();
    }

    private function getTemplateSmsService(): TemplateSmsService
    {
        return app(TemplateSmsService::class);
    }
}
